import http from 'axios'
// import router from '@/router'
import utils from '@/assets/utils'
import store from '@/store'
import { Notification } from 'element-ui'

http.defaults.baseURL = process.env.BASE_URL
http.defaults.withCredentials = true

http.interceptors.request.use(function (config) {
  let token = utils.getCookies('token')
  if (config.url.indexOf('/gt/register') !== -1 || config.url.indexOf('/gt/ajax-validate') !== -1) { // 不需要token的接口，删除token
    if (config.headers.common['Authorization']) {
      delete config.headers.common['Authorization']
    }
  } else {
    if (token) {
      config.headers.common['Authorization'] = 'Bearer ' + token
    }
  }
  return config
}, function (error) {
  return Promise.reject(error)
})

http.interceptors.response.use(function (response) {
  let res = response.data
  if (res.code !== 200) {
    Notification.error({
      title: '提示',
      message: res.message
    })
    if (res.code === 4001 || res.code === 4002) { // 4001:Token 过期了; // 4002 用户被禁用
      store.dispatch('LogOut').then(() => {
        $nuxt.$router.replace('/login')
      })
    }
  } else {
    return response
  }
}, function (error) {
  console.log(error.response)
  switch (error.response.status) {
    case 401:
      Notification.error({
        title: '401',
        message: error.response.data.message
      })
      store.dispatch('LogOut').then(() => {
        $nuxt.$router.replace('/login')
      })
      break
    case 500:
      Notification.error({
        title: '系统错误',
        message: error.response.data.message
      })
      break
    default:
  }
  return Promise.reject(error.response)
})
export default http
